/**
 * Copyright © 2021-2025 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.follow.service;

import com.jeeplus.security.util.SecurityUtils;
import com.jeeplus.sys.service.UserService;
import com.jeeplus.sys.service.dto.UserDTO;
import org.apache.catalina.security.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.kafka.KafkaProperties;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeeplus.follow.service.dto.FollowUpInfoDTO;
import com.jeeplus.follow.domain.FollowUpInfo;
import com.jeeplus.follow.mapper.FollowUpInfoMapper;

import java.security.Security;
import java.text.SimpleDateFormat;

/**
 * 回访信息Service
 * @author xx
 * @version 2023-12-30
 */
@Service
@Transactional
public class FollowUpInfoService extends ServiceImpl<FollowUpInfoMapper, FollowUpInfo> {

	@Autowired
	private UserService userService;

	/**
	 * 根据id查询
	 * @param id
	 * @return
	 */
	public FollowUpInfoDTO findById(String id) {
		return baseMapper.findById ( id );
	}

	/**
	 * 自定义分页检索
	 * @param page
	 * @param queryWrapper
	 * @return
	 */
	public IPage <FollowUpInfoDTO> findPage(Page <FollowUpInfoDTO> page, QueryWrapper queryWrapper) {
		queryWrapper.eq ("a.del_flag", 0 ); // 排除已经删除
		return  baseMapper.findList (page, queryWrapper);
	}

	public String getMyTask(String getType) {

		String loginName = SecurityUtils.getLoginName();
		UserDTO userDTO = userService.getUserByLoginName(loginName);
		String roleNames = userDTO.getRoleNames();

		if (roleNames.contains("医生")){
			getType = "doctor";
		}else if (roleNames.contains("病人")){
			getType = "patient";
		}else {
			return null;
		}

		FollowUpInfoDTO task = baseMapper.getMyTask(userDTO.getId(), getType);
		if (task != null){
			baseMapper.updateMessage(task.getId(), getType);

			// 创建SimpleDateFormat对象，定义日期时间格式
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			// 格式化Date对象为String
			String dateString = formatter.format(task.getFollowUpDate());

			String message = "您有一个回访【" + task.getFollowName() + "】将于" + dateString + "开始！";
			if (getType.equals("doctor")){
				UserDTO patientInfo = userService.get(task.getPatientId());
				message = message + "病人姓名：" + patientInfo.getName() + ",病人电话：" + patientInfo.getMobile();
			}
			return message;
		}

		return null;
	}
}
